import React, { useImperativeHandle, forwardRef, useState, useEffect } from 'react';
import { Text, View, ActivityIndicator, NativeModules, StyleSheet, Platform, Image, TextInput, PermissionsAndroid, TouchableHighlight, TouchableWithoutFeedback } from 'react-native'
import { connect } from 'react-redux'
import { pTx } from "../../utils/dimensions"
import { Popup, Badge } from '@pingtou/rn-vant'
import IconFont from '@pingtou/rn-vant-icons'
import LinearGradient from 'react-native-linear-gradient';
import { launchImageLibrary } from 'react-native-image-picker';
import httpApi from "../../api"
import crypto from 'crypto-js';
import RNFS from 'react-native-fs'
import { sha256, sha256Bytes } from 'react-native-sha256';

const mapState = state => {
    return {
    }
}

const ReleasePost = (props) => {
    const [loading, setLoading] = useState(false);
    const [post, setPost] = useState({
        postType: "0",
        content: "",
        repostId: "0"
    });
    const [curFiles, setCurFiles] = useState([]);

    const sha256 = (input) => {
        return crypto.SHA256(input).toString();
    }
    uploadMinio = async () => {
        try {
            if (!loading) {
                setLoading(true)
                if (curFiles.length > 0) {
                    var image = await httpApi.uploadMinio(curFiles)
                }
                const res = await httpApi.post({
                    postType: "0",
                    content: post.content,
                    image: image?.data.FileNames?.join(',') || "",
                    repostId: "0"
                })
                setLoading(false)
                setPost({
                    postType: "0",
                    content: "",
                    repostId: "0"
                })
                setCurFiles([])
                props.navigation.goBack()
            }
        } catch (error) {
            console.log(error)
        }
    }

    setCurFilesRemove = (index) => {
        let newCurFiles = JSON.parse(JSON.stringify(curFiles))
        newCurFiles.splice(index, 1)
        setCurFiles(newCurFiles)
    }

    cameraPermission = async () => {
        launchImageLibrary({
            mediaType: 'photo',
            quality: 1,
            videoQuality: 'low',
            includeBase64: true,
            selectionLimit: 9,
            storageOptions: {
                skipBackup: true,
            },
        }, res => {
            if (res.didCancel) {
                return false;
            } else {
                const assets = res.assets
                if (!assets) return
                for (let index = 0; index < assets.length; index++) {
                    if (curFiles.length < 9) {
                        setCurFiles([assets[index]].concat(curFiles))
                    }
                }
                calculateImageSHA256(assets[0])
                return
                // console.log(assets[0].uri)
                // const filePath = RNFS.DocumentDirectoryPath + assets[0].fileName;
                // console.log(filePath, "------------")
                // // RNFS.readFile(filePath, 'base64')
                // //     .then(data => {
                // const hash = crypto.createHash('sha256');
                // hash.update("data");
                // const sha256 = hash.digest('hex');
                // console.log('SHA256:', sha256);
                // //     })
                // //     .catch(err => {
                // //         console.error('Error reading file:', err);
                // //     });
                // return
                // const hashedMessage = sha256(assets[0].fileName)
                // httpApi.fileExist({ fileNames: assets[0].fileName, hashs: hashedMessage }).then(res => {
                //     console.log(res, "-------===")
                // })
                // console.log(hashedMessage, "---")
            }
        })
    }
    const calculateImageSHA256 = async (filePath) => {
        // // console.log(await RNFS.readFile(filePath.uri, 'ascii'))
        // RNFS.readFile(filePath.uri, 'ascii')
        //     .then(content => RNSha256.sha256(content))
        //     .then(hash => console.log('SHA-256 Hash:', hash))
        //     .catch(error => console.error('Error calculating SHA-256:', error));

        // return
        // console.log(sha256, sha256Bytes)
        RNFS.hash(filePath.uri, 'sha256')
            .then(async (data) => {
                console.log(data)
            })
            .catch(error => {
                console.error('Error calculating SHA256:', error);
            });
        return
        const fileStats = await RNFS.stat(filePath.uri);
        if (fileStats.isFile()) {
            const res = await RNFS.readFile(filePath.uri, 'base64');
            const buffer = Buffer.from(res, 'base64');
            buffer.buffer.slice(buffer.byteOffset, buffer.byteLength);
            console.log(buffer)
        }
        return

        return
        try {
            // 读取图片文件
            const imageData = await RNFS.readFile(imagePath.uri, 'base64');

            // 使用CryptoJS计算SHA256
            const imageHash = CryptoJS.SHA256(imageData).toString();
            httpApi.fileExist({ fileNames: imagePath.fileName, hashs: imageHash }).then(res => {
                console.log(res, "-------===")
            })
            console.log(imageHash)
            return imageHash;
        } catch (error) {
            console.error('Error calculating SHA256:', error);
            return null;
        }
    };


    requestCameraPermission = async () => {
        try {
            const granted = await PermissionsAndroid.request(
                PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
                {
                    title: '需要访问相册',
                    message: '需要访问相册',
                    buttonPositive: '',
                },
            )
            if (granted === PermissionsAndroid.RESULTS.GRANTED) {
            } else {
            }
        } catch (err) {
            console.warn(err)
        }
    }
    useEffect(() => {
        props.navigation.setOptions({
            headerRight: ({ options }) => (
                <View style={[styles.button]}>
                    {loading ? <ActivityIndicator size={pTx(14)} color="#fff" /> : <Text style={[styles.buttonStyle]} onPress={() => uploadMinio()}>发布</Text>}
                </View>
            )
        })
    }, [loading])
    useEffect(() => {
        if (Platform.OS === 'android') {
            requestCameraPermission()
        }
    })
    return (
        <View style={styles.page}>
            <TextInput
                rows={10}
                value={post.content}
                style={styles.input}
                multiline={true}
                placeholder="分享你的最新动态吧"
                onChangeText={value => setPost({ ...post, content: value })}
            />
            <View style={styles.listImage}>
                {
                    curFiles?.map((item, index) => {
                        return (
                            <TouchableWithoutFeedback key={index} onPress={() => setCurFilesRemove(index)} style={{ paddingHorizontal: pTx(2), marginVertical: 2 }} >
                                <Badge content={
                                    <IconFont name="cross" size={12} color="#fff" style={styles.cross} />
                                }>
                                    <Image
                                        style={styles.image}
                                        source={{ uri: item.uri }} />
                                </Badge>
                            </TouchableWithoutFeedback>

                        )
                    })
                }
                {
                    curFiles?.length < 9 ?
                        <TouchableWithoutFeedback onPress={this.cameraPermission}>
                            <Image
                                style={styles.image}
                                source={require('../../assets/image/icon15.png')} />
                        </TouchableWithoutFeedback>
                        : ""
                }

            </View>
        </View>
    );
}

export default ReleasePost

const styles = StyleSheet.create({
    page: {
        position: "relative",
        flex: 1,
        backgroundColor: "#fff",
    },
    button: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "center",
        minWidth: pTx(45),
        marginRight: pTx(15),
        height: pTx(30),
        borderRadius: pTx(6),
        backgroundColor: "rgba(58, 192, 48, 1)"
    },
    buttonStyle: {
        color: "#fff",
        fontSize: pTx(14),
    },
    input: {
        flex: 1,
        marginHorizontal: pTx(5),
        paddingHorizontal: pTx(25),
        paddingVertical: pTx(20),
        minHeight: pTx(105),
        maxHeight: pTx(200),
        fontSize: pTx(14),
        lineHeight: pTx(18),
        backgroundColor: "#fff",
        borderRadius: pTx(4),
        textAlignVertical: "top",
    },
    image: {
        width: pTx(90),
        height: pTx(90),
        marginHorizontal: pTx(10),
        marginVertical: pTx(10),
        padding: 0
    },
    listImage: {
        marginTop: pTx(15),
        flexDirection: 'row',
        alignItems: "center",
        flexWrap: "wrap",
        marginHorizontal: pTx(5),
        paddingHorizontal: pTx(15),
    },
    cross: {
        width: pTx(12),
        height: pTx(12),
        paddingVertical: pTx(130),
        fontSize: pTx(12),
        color: "#fff",
    }
})